<template>
  <PageWrapper dense contentFullHeight fixed-height>
    <BasicTable @register="registerTable">
      <template #toolbar>
        <div class="toolbar-defined">
          <a-button type="primary" @click="handleCreate">
            <template #icon><PlusOutlined /></template>
            {{ t('新增') }}
          </a-button>
          <a-button @click="handleDelete">{{ t('批量删除') }}</a-button>
        </div>
      </template>
      <template #action="{ record }">
        <TableAction
          :actions="[
            {
              icon: 'clarity:note-edit-line',
              onClick: handleEdit.bind(null, record),
            },
            {
              icon: 'ant-design:delete-outlined',
              color: 'error',
              onClick: handleDelete.bind(null, record),
            },
          ]"
        />
      </template>
    </BasicTable>

    <DataFirstModal
      v-if="state.isShowDataFirst"
      @register="registerDataFirst"
      @success="handleSuccess"
      @close="handleClose('isShowDataFirst')"
    />
    <CodeFirstModal
      v-if="state.isShowCodeFirst"
      @register="registerCodeFirst"
      @success="handleSuccess"
      @close="handleClose('isShowCodeFirst')"
    />
    <SimpleTemplateModal
      v-if="state.isShowSimpleTemplate"
      @register="registerSimpleTemplate"
      @success="handleSuccess"
      @close="handleClose('isShowSimpleTemplate')"
    />
    <!-- <CodeGeneratorModal
      v-if="state.isShowCodeGenerator"
      @register="registerCodeGenerator"
      @close="handleClose('isShowCodeGenerator')"
    /> -->
  </PageWrapper>
</template>
<script lang="ts" setup>
  import { BasicTable, useTable, TableAction, FormSchema, BasicColumn } from '/@/components/Table';

  import { PageWrapper } from '/@/components/Page';
  import { useMessage } from '/@/hooks/web/useMessage';
  import { useModal } from '/@/components/Modal';

  import DataFirstModal from '../dev/components/DataFirstModal.vue';
  import CodeFirstModal from '../dev/components/CodeFirstModal.vue';
  import SimpleTemplateModal from '../dev/components/SimpleTemplateModal.vue';
  // import CodeGeneratorModal from './components/CodeGeneratorModal.vue';
  import { h, onMounted, ref, createVNode, reactive, computed } from 'vue';

  import { FormDesignTypeEnum } from '/@/enums/formtypeEnum';
  import { Modal, Tag } from 'ant-design-vue';
  import { PlusOutlined, ExclamationCircleOutlined } from '@ant-design/icons-vue';
  import { useI18n } from '/@/hooks/web/useI18n';
  import { deleteCodeTemplate, getCodeTemplateList } from '/@/api/system/generator';
  import { useRouter } from 'vue-router';
  const { t } = useI18n();
  const { currentRoute } = useRouter();
  console.log(currentRoute.value.name, 'currentRoute');
  const codeType = computed(() => {
    const {
      value: { name },
    } = currentRoute;
    return name == 'simpleFirst'
      ? FormDesignTypeEnum.SIMPLE_TEMPLATE
      : name == 'styleFirst'
      ? FormDesignTypeEnum.CODE_FIRST
      : FormDesignTypeEnum.DATA_FIRST;
  });
  const title = computed(() => {
    return codeType.value == 2 ? '简易' : codeType.value == 1 ? '界面优先' : '数据优先';
  });

  const selectedKeys = ref<string[]>([]);

  const state = reactive({
    isShowDataFirst: true,
    isShowCodeFirst: true,
    isShowSimpleTemplate: true,
    isShowCodeGenerator: true,
  });
  const searchFormSchema: FormSchema[] = [
    {
      field: 'keyword',
      label: t('关键字'),
      component: 'Input',
      colProps: { span: 8 },
      componentProps: {
        placeholder: t('请输入关键字'),
      },
    },
  ];

  const columns: BasicColumn[] = [
    {
      dataIndex: 'name',
      title: t('功能名称'),
      align: 'left',
    },

    {
      dataIndex: 'description',
      title: t('功能描述'),
      align: 'left',
    },
    {
      dataIndex: 'categoryName',
      title: t('功能模块'),
      align: 'left',
    },
    {
      dataIndex: 'status',
      title: t('状态'),
      width: 120,
      customRender: ({ record }) => {
        const color = record.status == 1 ? 'blue' : 'yellow';
        const text = record.status == 1 ? '正常' : '草稿';
        return h(Tag, { color: color }, () => text);
      },
    },
    {
      dataIndex: 'remark',
      align: 'left',
      title: t('备注'),
    },
  ];
  const { notification } = useMessage();

  const [registerDataFirst, { openModal: openDataFirstModal }] = useModal();
  const [registerCodeFirst, { openModal: openCodeFirstModal }] = useModal();
  const [registerSimpleTemplate, { openModal: openSimpleTemplateModal }] = useModal();

  const [registerTable, { reload }] = useTable({
    title: t(title.value + '模板列表'),
    api: getCodeTemplateList,
    rowKey: 'id',
    columns,
    formConfig: {
      rowProps: {
        gutter: 16,
      },
      schemas: searchFormSchema,
      fieldMapToTime: [],
    },
    beforeFetch: (params) => {
      //发送请求默认新增
      return { ...params, type: codeType.value };
    },
    useSearchForm: true,
    showTableSetting: true,
    striped: false,
    actionColumn: {
      width: 80,
      title: t('操作'),
      dataIndex: 'action',
      slots: { customRender: 'action' },
    },
    rowSelection: {
      type: 'checkbox',
      onChange: onSelectChange,
    },
  });

  function onSelectChange(rowKeys: string[]) {
    selectedKeys.value = rowKeys;
  }

  function handleCreate() {
    switch (codeType.value) {
      case 0:
        openDataFirstModal(true, { undoAble: true });
        break;
      case 1:
        openCodeFirstModal(true, { undoAble: true });
        break;
      case 2:
        openSimpleTemplateModal(true, { undoAble: true });
        break;
    }
  }

  function handleEdit(record: Recordable) {
    switch (codeType.value) {
      case 0:
        openDataFirstModal(true, {
          id: record.id,
          isUpdate: true,
        });
        break;
      case 1:
        openCodeFirstModal(true, {
          id: record.id,
          isUpdate: true,
        });
        break;
      case 2:
        openSimpleTemplateModal(true, {
          id: record.id,
          isUpdate: true,
        });
        break;
    }
  }

  function handleDelete(record: Recordable = {}) {
    const ids = record.id ? [record.id] : selectedKeys.value;
    if (!ids.length) {
      noticeInfo(t('删除'));
      return;
    }
    Modal.confirm({
      title: t('提示'),
      icon: createVNode(ExclamationCircleOutlined),
      content: t('确定要删除所选项吗？'),
      onOk() {
        deleteCodeTemplate(ids).then(() => {
          reload();
          notification.success({
            message: t('提示'),
            description: t('删除成功'),
          });
        });
      },
      onCancel() {},
      okText: t('确认'),
      cancelText: t('取消'),
    });
  }

  function handleSuccess() {
    reload();
  }

  function handleClose(modal) {
    state[modal] = !state[modal];
    setTimeout(() => {
      state[modal] = !state[modal];
    }, 100);
  }

  // const templateJson = await getFormTemplate(formId.value);

  function noticeInfo(info: string) {
    notification.warning({
      message: t('提示'),
      description: t(`请先选择要{notice}的数据项`, { notice: info }),
    }); //提示消息
  }

  onMounted(() => {});
</script>
<style lang="less" scoped>
  .toolbar-defined {
    :deep(.ant-btn) {
      margin-left: 5px;
    }
  }
</style>
